﻿namespace PowerSong.UserInterface
    {
    using System;
    using System.Linq;
    using System.Windows;
    using DB = PowerSong.SongDatabase;

    /// <summary>
    /// Interaction logic for AddStyleWindow.xaml
    /// </summary>
    public partial class AddStyleWindow : Window
        {

        public SongDatabase.Style StyleCreated { get; private set; }

        public AddStyleWindow()
            {
            InitializeComponent();
            foreach (var style in State.Database.Styles.GetAllStyles().OrderBy(style => style.Name))
                {
                BasedOnComboBox.Items.Add(style);
                }
            if (BasedOnComboBox.Items.Count <= 0) BasedOnCheckBox.IsEnabled = false;
            }

        private void OKButton_Click(object sender, RoutedEventArgs e)
            {

            try
                {

                // Ensure a name has been specified
                if (string.IsNullOrEmpty(StyleNameTextBox.Text.Trim()))
                    {
                    throw new Exception("Please specify a name for this style.");
                    }

                // Ensure the name is unique
                if (State.Database.Styles.Contains(StyleNameTextBox.Text))
                    {
                    throw new Exception("There already exists a style named '" + StyleNameTextBox.Text + "'. Please enter a different name for this style.");
                    }

                // Start by creating a style based on default values
                var newStyle = StyleManager.CreateDefault(StyleNameTextBox.Text);
                if (BasedOnCheckBox.IsChecked == true)
                    {

                    // Create the style based on an existing style
                    var existingStyle = (DB.Style)BasedOnComboBox.SelectedItem;
                    existingStyle.CopyTo(newStyle);
                    newStyle.Name = StyleNameTextBox.Text;

                    }

                // Save the style
                State.Database.Styles.Write(newStyle);
                this.StyleCreated = newStyle;

                // Close the window
                this.DialogResult = true;

                }
            catch (Exception ex)
                {
                Utilities.ShowErrorMessage("Cannot Save Style Details", ex.Message);
                }

            }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
            {
            this.DialogResult = false;
            }

        private void BasedOnCheckBox_Checked(object sender, RoutedEventArgs e)
            {
            BasedOnComboBox.IsEnabled = true;
            }

        private void BasedOnCheckBox_Unchecked(object sender, RoutedEventArgs e)
            {
            BasedOnComboBox.IsEnabled = false;
            }

        }

    }
